<template>
  <div>
    <h3 align="center">购物车</h3>
    <goods
      v-for="(goods, index) in goodsList"
      :key="index"
      :goods="goods"
      @subGoods="subGoods"
      @addGoods="addGoods"
    ></goods>
    <div>商品的总价：{{ total }}</div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getGoodsList } from '@/api/goods2'
import Goods from '@/components/todos/Goods4.vue'
//data
let goodsList = ref([])
//computed
const total = computed(() => {
  var sum = 0
  this.goodsList.forEach((goods) => {
    sum += goods.price * goods.num
  })
  return sum
})
//使用onmouted来改造mounted
onMounted(async () => {
  //获取网络请求后的数据，对goodsList进行赋值
  getGoodsList(2).then((res) => {
    console.log(res.data)
    goodsList.value = res.data
  })
})

const addGoods = (id) => {
  //从goodlist中
  const goods = goodsList.value.find((item) => item.id == id)
  goods.num = goods.num + 1
}
const subGoods = (id) => {
  const goods = goodsList.value.find((item) => item.id == id)
  goods.num = goods.num - 1
}
</script>

<style lang="scss" scoped></style>
